from apriori import *
from pretreat import getData
def getRules(D,minsup,minconf):#根据最小支持度和最小置信度获取关联规则
    '''
    :param D: 事务数据集
    :param minsup: 最小支持度
    :param minconf: 最小置信度
    :return: R :关联规则
    '''
    def getSubset(s):  # 获取子集函数(采用二进制法)
        res, n = [], len(s)
        for state in range(2 ** n):
            subs = ""
            for i in range(n - 1, -1, -1):
                if state % 2 == 1:
                    subs += s[i]
                state >>= 1
            if subs and len(subs) != n:
                res.append(subs)
        return res
    def support_count(A):#计算项集A的支持度计数
        cnt=0
        for transcation in D:
            if set(A).issubset(set(transcation)):
                cnt+=1
        return cnt
    L=apriori(D,minsup) #获取频繁模式
    R=[]
    for l in L:
        for itemset in l:
            subset=getSubset(itemset) #求所有子集
            for s in subset: #s是其中一个子集
                t="".join(list(set(itemset)-set(s))) #t是s相对itemset的补集
                confidence=support_count(itemset)/support_count(s)
                if confidence>=minconf: #置信度不小于阈值
                    R.append(s+"=>"+t) #导出关联规则s=>t
    return R
D=getData()
minsup,minconf=0.6,0.85
R=getRules(D,minsup,minconf)
print(R)